package com.yao2san.sim.storage.client.core.uploader;

import com.yao2san.sim.storage.client.util.StorageUtil;
import com.yao2san.sim.storage.client.config.MinioProperties;
import com.yao2san.sim.storage.client.core.enums.StorageType;
import com.yao2san.sim.storage.client.core.event.UploadResult;
import com.yao2san.sim.storage.client.core.event.UploadEvent;
import com.yao2san.sim.storage.client.core.policy.FolderPolicy;
import com.yao2san.sim.storage.client.exception.UploadErrorException;
import com.yao2san.sim.storage.client.util.StorageUtil;
import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import static io.minio.ObjectWriteArgs.MIN_MULTIPART_SIZE;

@Slf4j
public class MinioUploader extends AbstractUploader {

    private final MinioProperties minioProperties;
    private final MinioClient client;

    private final ApplicationContext applicationContext;

    private final FolderPolicy folderPolicy;

    public MinioUploader(MinioClient client, MinioProperties minioProperties, ApplicationContext applicationContext, FolderPolicy folderPolicy) {
        this.client = client;
        this.minioProperties = minioProperties;
        this.applicationContext = applicationContext;
        this.folderPolicy = folderPolicy;
    }

    @Override
    public UploadResult upload(InputStream stream, String dest, UploadArgs args) throws IOException, UploadErrorException {
        StorageUtil.checkObjectName(dest);
        try {
            String object = getObject(dest, args);
            String bucket = minioProperties.getBucket();

            PutObjectArgs.Builder builder = PutObjectArgs.builder()
                    .bucket(bucket)
                    .object(object)
                    .stream(stream, -1, MIN_MULTIPART_SIZE);
            if (args != null) {
                builder.userMetadata(args);
                if (StringUtils.isNotEmpty(args.getContentType())) {
                    builder.contentType(args.getContentType());
                }
            }
            //upload
            ObjectWriteResponse response = client.putObject(builder.build());
            //state
            StatObjectResponse statObject = client.statObject(StatObjectArgs.builder()
                    .bucket(bucket)
                    .object(response.object())
                    .build());
            //publish event
            UploadResult result = UploadResult.builder()
                    .object(response.object())
                    .size(statObject.size())
                    .url(response.region())
                    .uploadArgs(args)
                    .success(true)
                    .build();
            applicationContext.publishEvent(new UploadEvent(result));

            if (args != null && args.getCallback() != null) {
                args.getCallback().callback(result);
            }
            return result;
        } catch (ErrorResponseException | NoSuchAlgorithmException |
                 InsufficientDataException | InternalException |
                 InvalidKeyException | InvalidResponseException |
                 IOException | ServerException | XmlParserException e) {

            //publish event
            UploadResult result = UploadResult.builder()
                    .success(false)
                    .message(e.getMessage())
                    .build();
            applicationContext.publishEvent(new UploadEvent(result));

            log.error("file upload error", e);
            throw new UploadErrorException(e);
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    private String getObject(String dest, UploadArgs args) {
        String dir = this.folderPolicy.create();
        String name = FilenameUtils.getName(dest);
        String path = FilenameUtils.getPath(dest);
        if (args != null) {
            FolderPolicy fp = args.getFolderPolicy();
            if (fp != null) {
                dir = fp.create();
            }
        }
        String object = getBasePath() + "/" + dir + "/" + path + "/" + name;
        return StorageUtil.formatPath(object);
    }

    @Override
    public String getBasePath() {
        return minioProperties.getPath();
    }

    @Override
    public String getName() {
        return StorageType.MINIO.name();
    }
}
